import React, { useMemo, useCallback, useRef } from 'react';
import GridTransfer from '@/components/gridtransfer';
import { allOperators } from '@/components/searchform/operators';
import { SupportFilterField, SearchField } from '@/components/searchform/interface';
import { get } from 'lodash';
import { UISchema } from 'gantd/lib/schema-form';

interface TransferProps {
  height: number | string;
  supportFilterFields: SupportFilterField[]; // 支持查询字段
  searchFields: SearchField[]; // 已配置的查询字段
  showOperatorColumn: boolean; // 显示操作列
  onChange: (searchFields: SearchField[]) => void;
  uiSchema: UISchema; // 表单的UI配置
}

const checkRequired = (params: any) => {
  const required = get(params, 'data.required');
  return !required;
};

const columns = [
  {
    title: tr('查询条件名称'),
    fieldName: 'title',
    flex: 1,
    sortable: false,
    menuTabs: [],
    rowDrag: checkRequired,
  },
  {
    title: tr('操作符'),
    fieldName: 'operator',
    width: 80,
    sortable: false,
    menuTabs: [],
  },
];

/**
 * 查询字段穿梭框
 * @param props
 */
export default function (props: TransferProps) {
  const { height, supportFilterFields, searchFields, showOperatorColumn, onChange, uiSchema } = props;

  const supportFilterFieldsMapRef = useRef<any>({});
  // 记录col配置为0的字段配置列表
  const col0SchemaItemsRef = useRef<any[]>([]);

  // col配置为0的字段名列表
  const col0Fields = useMemo(() => {
    let res = Object.entries(uiSchema).reduce((res, [key, item]) => {
      const col = get(item, 'field:col');
      if (col === 0) {
        res.push(key as string);
      }
      return res;
    }, [] as string[]);
    return res;
  }, [uiSchema]);

  const targetKeys = useMemo(() => {
    return searchFields.map((item) => item.fieldName).filter((item) => !col0Fields.includes(item)); // 这里需要过滤掉col配置为0的字段
  }, [searchFields, col0Fields]);

  const [leftColumns, rightColumns] = useMemo(() => {
    const left = columns
      .filter((item) => {
        const { fieldName } = item;
        return showOperatorColumn ? true : ['title'].includes(fieldName);
      })
      .map((item: any) => {
        const { fieldName } = item;
        const obj: any = {};
        if (fieldName === 'title') {
          obj.filter = 'agTextColumnFilter';
          obj.menuTabs = ['filterMenuTab'];
        }
        return {
          ...item,
          ...obj,
        };
      });
    const right = columns.filter((item) => {
      const { fieldName } = item;
      return showOperatorColumn ? true : ['title'].includes(fieldName);
    });
    return [left, right];
  }, [showOperatorColumn, col0Fields]);

  useMemo(() => {
    const obj = {};
    col0SchemaItemsRef.current = [];
    supportFilterFields.forEach((item) => {
      const { fieldName } = item;
      obj[fieldName] = item;
      if (col0Fields.includes(fieldName)) {
        col0SchemaItemsRef.current.push(item);
      }
    });
    supportFilterFieldsMapRef.current = obj;
  }, [supportFilterFields, col0Fields]);

  const left = useMemo(() => {
    return {
      title: tr('待选条件'),
      extraGridProps: {
        columns: leftColumns,
      },
    };
  }, []);

  // 合并正常改变的字段与col配置为0的字段
  const mergeCol0FieldsChange = useCallback(
    (res: any[]) => {
      let newRes = [...res, ...col0SchemaItemsRef.current];
      onChange && onChange(newRes);
    },
    [onChange],
  );

  const onChange_ = useCallback(
    (resKeys: string[]) => {
      const map = supportFilterFieldsMapRef.current;
      const res: SearchField[] = resKeys.map((item) => map[item]).filter((item) => item);
      mergeCol0FieldsChange(res);
    },
    [supportFilterFields, mergeCol0FieldsChange, targetKeys],
  );

  const onSortChange = useCallback(
    (resKeys: string[], direction: 'left' | 'right') => {
      if (direction === 'right') {
        const map = supportFilterFieldsMapRef.current;
        const res: SearchField[] = resKeys.map((item) => map[item]).filter((item) => item);
        mergeCol0FieldsChange(res);
      }
    },
    [supportFilterFields, mergeCol0FieldsChange, targetKeys],
  );

  const right = useMemo(() => {
    return {
      title: tr('已选条件'),
      extraGridProps: {
        columns: rightColumns,
        isRowSelectable: checkRequired,
      },
    };
  }, [col0Fields]);

  const dataSource = useMemo(() => {
    const res = supportFilterFields
      // 需要过滤掉col配置为0的字段
      .filter((item) => !col0Fields.includes(item.fieldName))
      .map((supportFilterField) => {
        const { title, operator = 'EMPTY', fieldName, required } = supportFilterField;
        const tempOperator = allOperators[operator];
        const rulesRequired = get(supportFilterField, 'options.rules', []).some(
          (item: { required: any }) => item.required,
        );
        return {
          fieldName,
          title,
          operator: tempOperator.symbol || tempOperator.name,
          required: required || rulesRequired,
        };
      });
    return res;
  }, [supportFilterFields, col0Fields]);

  return (
    <GridTransfer
      transKey="feildTransfer"
      height={height}
      rowKey="fieldName"
      left={left}
      right={right}
      dataSource={dataSource}
      targetKeys={targetKeys}
      onChange={onChange_}
      onSortChange={onSortChange}
    />
  );
}
